package attribute

import (
	"context"
	"time"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/product/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/product/rpc/productclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetAttributeByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAttributeByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAttributeByIdLogic {
	return &GetAttributeByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetAttributeByIdLogic) GetAttributeById(req *types.IDReq) (resp *types.AttributeInfoResp, err error) {
	if req.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	data, err := l.svcCtx.ProductRpc.BackendGetAttributeById(l.ctx, &productclient.AttributeIdReq{
		Id:         req.Id,
		WithOption: pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return nil, err
	}

	var opts []*types.AttributeOptionInfo
	if len(data.Options) > 0 {
		for _, v := range data.Options {
			opts = append(opts, &types.AttributeOptionInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        v.Id,
					CreatedAt: v.CreatedAt,
				},
				AttributeId: v.AttributeId,
				Name:        v.Name,
				Slug:        v.Slug,
				Sort:        v.Sort,
				Status:      v.Status,
			})
		}
	}

	option := util.GetOptionByStatusAndId(data.Status, 0)

	return &types.AttributeInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.AttributeInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			TermId:      data.TermId,
			Taxonomy:    data.Taxonomy,
			IsVariation: data.IsVariation,
			Name:        data.Name,
			Slug:        data.Slug,
			HasImage:    data.HasMedia,
			Sort:        data.Sort,
			Status:      data.Status,
			Loaded:      pointy.GetPointer(modelx.FormatTime(time.Now(), "")),
			Options:     opts,
		},
	}, nil
}
